﻿// --------------
// 作者:Vitity
// --------------

using NICWebApi.Extensions.Caching.Options;

using System.Reflection;

internal static class Utils
{
    /// <summary>
    /// 配置节名称
    /// </summary>
    internal const string OptionSection = "Caching";

    /// <summary>
    /// 获取当前目录下所有Json文件
    /// </summary>
    /// <returns></returns>
    public static string[] GetJsonFiles()
    {
        var matcher = new Matcher();
        matcher.AddInclude("**/*.json");
        var jsonFiles = matcher.GetResultsInFullPath(AppContext.BaseDirectory).ToArray();
        return jsonFiles;
    }

    /// <summary>
    /// 获取Json文件配置
    /// </summary>
    /// <returns></returns>
    public static CachingOptions GetOptions()
    {
        var jsonFiles = GetJsonFiles();
        CachingOptions options = default;

        foreach (var jsonFile in jsonFiles)
        {
            try
            {
                var configuration = new ConfigurationBuilder()
                    .AddJsonFile(jsonFile, optional: false, reloadOnChange: true)
                    .Build();

                options = configuration.GetSection(OptionSection).Get<CachingOptions>();
                if (options != null)
                {
                    break;
                }
            }
            catch
            {
                // 忽略读取失败的文件
                continue;
            }
        }

        // 如果没有找到配置，返回默认配置
        return options ?? new CachingOptions();
    }

    /// <summary>
    /// 获取所有程序集
    /// </summary>
    /// <returns>程序集集合</returns>
    public static Assembly[] GetAllAssemblies()
    {
        var assemblies = new List<Assembly>();
        // 获取所有程序集
        assemblies = AppDomain.CurrentDomain.GetAssemblies()
                                .Where(ass =>
                                        !ass.FullName.StartsWith(nameof(System))
                                        && !ass.FullName.StartsWith(nameof(Microsoft))
                                        && !ass.FullName.StartsWith("netstandard"))
                                .Distinct().ToList();
        // 添加入口程序集
        var entryAssembly = Assembly.GetEntryAssembly();
        if (entryAssembly != null && !assemblies.Contains(entryAssembly))
        {
            assemblies.Add(entryAssembly);
        }

        return assemblies.ToArray();
    }
}